package com.service.uai.engine.comm;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.bpms.common.CommonUtil;
import com.bpms.common.Param;
import com.bpms.eai.ISyncComm;
import com.bpms.eai.PackTool;

public class ATMClient extends PackTool implements ISyncComm {

	public byte[] sendBuffer(byte[] buffer) {
		Socket st = null;
		OutputStream outputStream = null;
		int port = Integer
		.parseInt(Param.getValue("UAI", "atm_send_port"));
		String ip=Param.getValue("UAI", "atm_send_ip");
		int timeout =Integer.parseInt(Param.getValue("UAI", "atm_send_timeout"));
		try{
			CommonUtil.debug("ATMClient.ip:"+ip+":"+port);
			
			st = new  Socket(ip,port);
			st.setSoTimeout(timeout*1000);
			
			CommonUtil.debug("ATMClient.sendBuf("+new String(buffer).length()+")"+new String(buffer));
			
//			开始发送

			outputStream = st.getOutputStream();
			OutputStream dataOutputStream = new DataOutputStream(
					new BufferedOutputStream(outputStream));
//			OutputStream dataOutputStream = new DataOutputStream(outputStream);
//					new BufferedOutputStream());
			//delphi发送规则
//			int buffsize = myByte.toInteger(buffer);
//			byte[] buff=myByte.byteCon(myByte.toBytes(buffsize), buffer);
			
			dataOutputStream.write(buffer);
			dataOutputStream.flush();
//			
			byte[] bbodylen=new byte[8];
			int len=st.getInputStream().read(bbodylen, 0, 8);
			if(len<8)
			{
				CommonUtil.debug("atmclent the receive bodylen is short "+new String(bbodylen));
				return null;
			}
			String sbodylen=new String(bbodylen);
			int ibodylen=Integer.parseInt(sbodylen);
			CommonUtil.debug("atmclent receive bodylens is ："+new String(bbodylen));
			
			byte[] head = new byte[4];
			int headlen;
			headlen = st.getInputStream().read(head, 0, 4);
			if (headlen < 4) {
				CommonUtil.debug("atmclent the head len is short "+ new String(head,"GBK"));
				return null;
			}
			String shead=new String(head);
			CommonUtil.debug("atmclent the head :"+ shead);
			
			byte[] result = new byte[4];
			len = st.getInputStream().read(result, 0, 4);
			if (len < 4) {
				CommonUtil.debug("atmclent the result len is short "+ new String(result,"GBK"));
				return null;
			}
			String sresult=new String(result);
			CommonUtil.debug("atmclent the sresult :"+ sresult);
			
			byte[] body1=new byte[ibodylen-8];
			len = st.getInputStream().read(body1, 0, ibodylen-8);
			if (len < ibodylen-8) {
				CommonUtil.debug(shead+" atmclent read body1 length short,len="+len+new String(body1));
				return null;
			}

			CommonUtil.debug("atmclent read body1="+new String(body1));
			return memmerge(memmerge(bbodylen,head),body1);
			
		}catch(Exception e){
			CommonUtil.debug("ATMClient.sendBuffer exception",e);
			return null;
		}
		
	}

}
